package cn.conac.rc.gateway.security.rest;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.DesUtil;
import cn.conac.rc.framework.utils.FastJsonUtil;
import cn.conac.rc.framework.utils.IdGen;
import cn.conac.rc.framework.utils.IpUtils;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.framework.utils.ValidatorUtil;
import cn.conac.rc.gateway.config.propertiesConfig;
import cn.conac.rc.gateway.modules.common.service.AreaService;
import cn.conac.rc.gateway.modules.common.service.SmsService;
import cn.conac.rc.gateway.modules.common.service.UserCommonService;
import cn.conac.rc.gateway.modules.common.vo.SmsBean;
import cn.conac.rc.gateway.modules.common.vo.UserVo;
import cn.conac.rc.gateway.modules.user.entity.UserEntity;
import cn.conac.rc.gateway.modules.user.service.UserService;
import cn.conac.rc.gateway.modules.user.vo.UserInfoVo;
import cn.conac.rc.gateway.security.JwtTokenUtil;
import cn.conac.rc.gateway.security.RedisUtil;
import cn.conac.rc.gateway.security.UserUtils;
import cn.conac.rc.gateway.security.ValidateCodeUtils;
import cn.conac.rc.gateway.security.service.SiDomainUserService;
import cn.conac.rc.gateway.security.vo.JwtAuthRequest;
import cn.conac.rc.gateway.security.vo.JwtUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(tags = "用户认证相关接口", description = "共通")
public class AuthRestController
{
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private propertiesConfig properties;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SiDomainUserService siService;

    @Autowired
    private UserCommonService userCommonService;

    @Autowired
    private UserService userService;

    @Autowired
    AreaService areaService;


    @Autowired
    SmsService smsService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    ValidateCodeUtils validateCodeUtils;

    @ApiOperation(value = "(APP)用户认证，成功返回JwtToken", httpMethod = "POST", response = JwtUser.class, notes = "根据id获取资源详情")
    @RequestMapping(value = "public/auth", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(
            @ApiParam("用户名和密码") @RequestBody JwtAuthRequest authenticationRequest, @ApiParam("不用填，系统使用") Device device)
            throws AuthenticationException
    {
        ResultPojo result = new ResultPojo();
        //TODO 验证码校验
        // 格式校验
//        String valResult = ValidatorUtil.validate(authenticationRequest);
//        if (valResult != null) {
//            result.setCode(ResultPojo.CODE_FAILURE);
//            result.setMsg(valResult);
//            return ResponseEntity.ok(result);
//        }
        String userid = "";
        String username = authenticationRequest.getUsername();
        String password = authenticationRequest.getPassword();

        if (username.endsWith(".政务") || username.endsWith(".公益")) {
            //1. 调用SI接口验证登录信息
            JSONObject jsStr =
                    siService.getSiDomainUser(username.split("\\.")[0], "." + username.split("\\.")[1], password);
            String status = jsStr.getString("code");
            if (!"100000".equals(status)) {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setResult(siService.getMsgByCode(status));
                JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                return ResponseEntity.ok(jsonObj);
            } else {
                //成功
                jsStr = jsStr.getJSONObject("domainUserInfo_record");
                System.out.println(JSON.toJSONString(jsStr));
                String userCode = jsStr.getString("userCode");
                String companyName = jsStr.getString("companyName");
                JSONObject userJson = userCommonService.getUserByUserCode(userCode);
                UserVo user = null;
                if (userJson.getString("code").equals(ResultPojo.CODE_SUCCESS)
                        && userJson.getJSONArray("result") != null)
                {
                    List<UserVo> list =
                            FastJsonUtil.getList(userJson.getJSONArray("result").toJSONString(), UserVo.class);
                    if (list.size() == 1) {
                        user = list.get(0);
                    } else {
                        for (int i = 0; i < list.size(); i++) {
                            UserVo tmp = list.get(i);
                            if (tmp.getLoginName().equals(companyName)) {
                                user = tmp;
                                break;
                            } else if (tmp.getLoginName().endsWith("_si")) {
                                user = tmp;
                            }
                        }
                    }
                }
                if (user != null) {
                    username = user.getLoginName();
                    userid = user.getId();
//                    String identity = jsStr.getString("identity");
                    //委办局登录identity:1标识编办用户0orNULL标识非编办用户
//                    if (!"1".equals(identity)) {
//                        result.setCode(ResultPojo.CODE_FAILURE);
//                        result.setResult("输入信息有误，请使用账号方式登录");
//                        JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
//                        return ResponseEntity.ok(jsonObj);
//                    }
                } else {
                    //TODO 跳转至添加用户页面
                    result.setCode(ResultPojo.CODE_FAILURE);
                    result.setResult("用户不存在");
                    JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                    return ResponseEntity.ok(jsonObj);
                }
            }
        } else {
            JSONObject userJson = userCommonService.getLoginUser(username);
            UserVo user = null;
            if (userJson.getString("code").equals(ResultPojo.CODE_SUCCESS)
                    && userJson.getJSONObject("result") != null)
            {
                user = userJson.getJSONObject("result").toJavaObject(UserVo.class);
            }

            if (user != null) {
                userid = user.getId();
                //loginCount = user.getLoginCount();
            } else {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setResult("用户不存在");
                JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                return ResponseEntity.ok(jsonObj);
            }
        }
        // Perform the security
        JSONObject jsonObj = null;
        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(userid,
                        password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        // final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        final JwtUser userDetails = (JwtUser) userDetailsService.loadUserByUsername(userid);
        final String token = jwtTokenUtil.generateToken(userDetails, device);
        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(token);
        jsonObj = (JSONObject) JSONObject.toJSON(result);
        jsonObj.put("claims", jwtTokenUtil.getClaimsFromToken(token));
        // Return the token
        return ResponseEntity.ok(jsonObj);
    }

    @ApiOperation(value = "用户认证，成功返回JwtToken", httpMethod = "POST", response = JwtUser.class, notes = "根据id获取资源详情")
    @RequestMapping(value = "public/login", method = RequestMethod.POST)
    public ResponseEntity<?> cudCreateAuthenticationToken(HttpServletRequest request,
            @ApiParam("用户名和密码") @RequestBody JwtAuthRequest authenticationRequest, @ApiParam("不用填，系统使用") Device device)
            throws AuthenticationException, Exception
    {
        ResultPojo result = new ResultPojo();
        // 格式校验
        String valResult = ValidatorUtil.validate(authenticationRequest);
        if (valResult != null) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg(valResult);
            JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
            return ResponseEntity.ok(jsonObj);
        }
        String userid = "";
        String username = authenticationRequest.getUsername();
        String password = authenticationRequest.getPassword();
        String validateKey = DesUtil.desEncrypt(authenticationRequest.getValidateKey(), null);
        String validateCode = authenticationRequest.getValidateCode();
        String loginType = authenticationRequest.getLoginType();
        String fourNum = authenticationRequest.getFourNum();
        Integer loginCount = 0;
        String code = "";
        if ("2".equals(loginType)) {
            code = (String) redisUtil.get("RC_SMS_CODE_" + username + validateKey);
            redisUtil.remove("RC_SMS_CODE_" + username + validateKey);
        }else{
            code = (String) redisUtil.get("RC_IMG_CODE" + validateKey);
            redisUtil.remove("RC_IMG_CODE" + validateKey);
        }
        if (!properties.getDefaultVcode().equals(validateCode) && StringUtils.isBlank(code) && StringUtils.isBlank(fourNum)) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("验证码失效，请刷新重试！");
            JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
            return ResponseEntity.ok(jsonObj);
        }
        if (!properties.getDefaultVcode().equals(validateCode) && !validateCodeUtils.validate(code, validateCode) && StringUtils.isBlank(fourNum)) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("验证码错误！");
            JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
            return ResponseEntity.ok(jsonObj);
        } else {
            //图片验证码验证成功,删除redis中缓存的图片验证码
//            redisUtil.remove(validateKey);
        }
        if ("1".equals(loginType)) {
            //用户名登录
            if(username.startsWith("rc_")){
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setMsg("请使用编制域名或者手机号登录");
                result.setResult(null);
            }
            JSONObject userJson = userCommonService.getLoginUser(username);
            UserVo user = null;
            if (userJson.getString("code").equals(ResultPojo.CODE_SUCCESS)
                    && userJson.getJSONObject("result") != null)
            {
                user = userJson.getJSONObject("result").toJavaObject(UserVo.class);
            }

            if (user != null) {
                userid = user.getId();
                loginCount = user.getLoginCount();
            } else {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setMsg("您输入的账号/密码错误，请重新输入");
                result.setResult(null);
                JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                return ResponseEntity.ok(jsonObj);
            }
        } else if ("2".equals(loginType)) {
            //1.根据手机号码查询用户信息
            JSONObject userJson = userService.findByMobile(username);
            UserVo user = null;
            if (userJson.getString("code").equals(ResultPojo.CODE_SUCCESS) && userJson.getJSONObject("result")!=null) {
                user = FastJsonUtil.getObject(userJson.getJSONObject("result").toJSONString(), UserVo.class);
            }
            if (user != null) {
                userid = user.getId();
                loginCount = user.getLoginCount();
                userid = userid + "_phone";
            } else {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setMsg("您输入的账号/密码错误，请重新输入");
                result.setResult(null);
                JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                return ResponseEntity.ok(jsonObj);
            }
        } else {
            //1. 调用SI接口验证登录信息
            String adminUserName = "";
            String adminOrgName = "";
            String admin = "";
            if ("3".equals(loginType)) {
                adminUserName = username.split("\\.")[0];
                adminOrgName = username.split("\\.")[1];
                admin = username.split("\\.")[2];
            } else {
                adminOrgName = username.split("\\.")[0];
                admin = username.split("\\.")[1];
            }
            JSONObject jsStr =
                    siService.getSiDomainUser(adminOrgName, "." + admin, password);
            String status = jsStr.getString("code");
            if ("110030".equals(status) || "110099".equals(status)) {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setMsg(siService.getMsgByCode(status));
                JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                return ResponseEntity.ok(jsonObj);
            } else {
                //成功
                jsStr = jsStr.getJSONObject("domainUserInfo_record");
                System.out.println(JSON.toJSONString(jsStr));
                String userCode = jsStr.getString("userCode");
                String companyName = jsStr.getString("companyName");
                JSONObject userJson = null;
                if ("3".equals(loginType)) {
                    userJson = userCommonService.getUserByUserCodeFullname(userCode, adminUserName);
                } else {
                    userJson = userCommonService.getUserByUserCode(userCode);
                }
                List<UserVo> userList = new ArrayList<UserVo>();
                String isRepeat = "";
                if (userJson != null && userJson.getString("code").equals(ResultPojo.CODE_SUCCESS)) {
                    List<UserVo> list =
                            FastJsonUtil.getList(userJson.getJSONArray("result").toJSONString(), UserVo.class);
                    if (list.size() == 1) {
                        userList = list;
                    } else {
                        if(list.size() > 1){
                            //重复，需要输入个人身份证号
                            isRepeat = "1";
                        }
                        for (int i = 0; i < list.size(); i++) {
                            UserVo tmp = list.get(i);

                            if ("3".equals(loginType)) {
                                //编制域名 0
                                if ("0".equals(tmp.getIsAdmin()) && tmp.getIsDisabled()==0 && tmp.getPassword().equals(DigestUtils.md5Hex(password)))
                                {
                                    userList.add(tmp);
                                }
                            } else {
                                //机构域名 1
                                if ("1".equals(tmp.getIsAdmin()))
                                {
                                    userList.add(tmp);
                                    break;
                                } else if (tmp.getLoginName().endsWith("_si")) {
                                    userList.add(tmp);
                                }
                            }
                        }
                    }
                }
                if (userList != null && userList.size() > 0) {
                    UserVo user = userList.get(0);
                    if (userList.size() > 1) {

                        if (StringUtils.isBlank(fourNum) && !user.getPassword()
                                .equals(DigestUtils.md5Hex(properties.getDefaultPwd())))
                        {
                            //TODO 机构域名重复，需要验证手机号码后4位

                            result.setCode(ResultPojo.CODE_SUCCESS_USER_REPEAT);
                            result.setMsg("请输入手机号码后4位");
                            return ResponseEntity.ok(result);
                        } else if (StringUtils.isNotBlank(fourNum) && !user.getPassword()
                                .equals(DigestUtils.md5Hex(properties.getDefaultPwd())))
                        {
                            user = null;
                            for (int i = 0; i < userList.size(); i++) {
                                UserVo userTmp = userList.get(i);
                                if (userTmp.getMobile().endsWith(fourNum)) {
                                    user = userTmp;
                                }
                            }
                            if (user == null) {
                                result.setCode(ResultPojo.CODE_FAILURE);
                                result.setMsg("手机号码不匹配");
                                JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                                return ResponseEntity.ok(jsonObj);
                            }
                        }
                    }

//                    String identity = jsStr.getString("identity");
                    //委办局登录identity:1标识编办用户0orNULL标识非编办用户
//                    if (!"1".equals(identity)) {
//                        result.setCode(ResultPojo.CODE_FAILURE);
//                        result.setMsg("输入信息有误，请使用账号方式登录");
//                        result.setResult(null);
//                        JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
//                        return ResponseEntity.ok(jsonObj);
//                    }
                    userid = user.getId();
                    if (StringUtils.isNotBlank(isRepeat) && "1".equals(isRepeat)) {
                        userid = userid + "_repeat";
                    }
                    loginCount = user.getLoginCount();
                } else {
                    //TODO 跳转至添加用户页面
                    result.setCode(ResultPojo.CODE_FAILURE);
                    result.setMsg("您输入的账号/密码错误，请重新输入");
                    result.setResult(null);
                    JSONObject jsonObj = (JSONObject) JSONObject.toJSON(result);
                    return ResponseEntity.ok(jsonObj);
                }
            }
        }
        // Perform the security
        JSONObject jsonObj = null;
        try {

            final Authentication authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(userid,
                            password));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (DisabledException e) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("账号被禁用无法登录");
            result.setResult(null);
            jsonObj = (JSONObject) JSONObject.toJSON(result);
            return ResponseEntity.ok(jsonObj);
        }

        // Reload password post-security so we can generate token
        final JwtUser userDetails = (JwtUser) userDetailsService.loadUserByUsername(userid);
        final String token = jwtTokenUtil.generateToken(userDetails, device);
        UserInfoVo userInfoVo = new UserInfoVo();
        UserEntity userEntity = new UserEntity();
        userEntity.setLoginCount(++loginCount);
        userEntity.setLastLoginIp(IpUtils.getRemoteAddr(request));
        userEntity.setLastLoginTime(new Date());
        // 保存用户信息-修改登录次数
        if (userid.endsWith("_phone") || userid.endsWith("_repeat")) {
            userid = userid.split("_")[0];
        }
        userInfoVo.setUserEntity(userEntity);
        JSONObject retUserInfoJson = userService.updateUserInfo(Integer.valueOf(userid), userInfoVo);
        if (!retUserInfoJson.getString("code").equals(ResultPojo.CODE_SUCCESS)) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setResult("数据异常。");
            jsonObj = (JSONObject) JSONObject.toJSON(result);
            return ResponseEntity.ok(jsonObj);
        }
        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(token);

        jsonObj = (JSONObject) JSONObject.toJSON(result);
        jsonObj.put("claims", jwtTokenUtil.getClaimsFromToken(token));
        // Return the token
        return ResponseEntity.ok(jsonObj);
    }

    @ApiOperation(value = "刷新登录token的过期时间，返回新的token", httpMethod = "POST", response = JwtUser.class, notes = "根据id获取资源详情")
    @RequestMapping(value = "auth/refresh", method = RequestMethod.POST)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request, @ApiParam("不用填，系统使用") Device device)
    {
        ResultPojo result = new ResultPojo();

        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        JwtUser user = UserUtils.getCurrentUser();
        
        //重新加载用户 生成token
        JwtUser userDetails = (JwtUser) userDetailsService.loadUserByUsername(user.getId());
        token = jwtTokenUtil.generateToken(userDetails, device);
        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(token);
        JSONObject jsonObj = jsonObj = (JSONObject) JSONObject.toJSON(result);
        jsonObj.put("claims", jwtTokenUtil.getClaimsFromToken(token));
        return ResponseEntity.ok(jsonObj);
        
       /* 

        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
            String refreshedToken = jwtTokenUtil.refreshToken(token);

            result.setCode(ResultPojo.CODE_SUCCESS);
            result.setResult(refreshedToken);
            return ResponseEntity.ok(result);
        } else {
            result.setCode(ResultPojo.CODE_FAILURE);
            return ResponseEntity.badRequest().body(result);
        }*/
    }

    @ApiOperation(value = "获取图片验证码", httpMethod = "GET", notes = "获取图片验证码")
    @RequestMapping(value = "public/jcaptcha/img/{key}", method = RequestMethod.GET)
    public ResponseEntity<?> getImgJcaptcha(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("key") String key)
    {
        ResultPojo result = new ResultPojo();
        String code = "";
        try {
            key = DesUtil.desEncrypt(key, null);
            code = validateCodeUtils.createImage(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将验证码存储redis中有效期1小时
        redisUtil.set("RC_IMG_CODE" + key, code, properties.getImglongtime());
        return null;
    }

    @ApiOperation(value = "获取短信验证码", httpMethod = "GET", notes = "获取短信验证码")
    @RequestMapping(value = "public/jcaptcha/msg/{phoneNum}/{key}", method = RequestMethod.GET)
    public ResponseEntity<?> getMsgJcaptcha(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("phoneNum") String phoneNum,
            @PathVariable("key") String key)
    {
        ResultPojo result = new ResultPojo();
        SmsBean smsBean = new SmsBean();
        smsBean.setMobile(phoneNum);
        smsBean.setSmsTemplate("content-auth");
        Map<String, String> parameter = new HashMap<String, String>();
        String code = Integer.valueOf(Math.round(Math.random() * 9000 + 1000) + "") + "";
        parameter.put("checkCode", code);
        parameter.put("time", properties.getSmstime());
        smsBean.setMap(parameter);
        if(StringUtils.isNotBlank(properties.getDefaultSendsms()) && "1".equals(properties.getDefaultSendsms())){
            smsService.sendSms(smsBean);
        }
        System.out.println(code);
        try {
            key = DesUtil.desEncrypt(key, null);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResultPojo.CODE_FAILURE);
            return ResponseEntity.ok().body(result);
        }
        //将验证码存储redis中有效期60秒
        redisUtil.set("RC_SMS_CODE_" + phoneNum + key, code, properties.getSmslongtime());
        result.setCode(ResultPojo.CODE_SUCCESS);
        return ResponseEntity.ok().body(result);
    }

    @ApiOperation(value = "获取当前登录用户状态信息", httpMethod = "GET", response = JwtUser.class, notes = "根据id获取资源详情")
    @RequestMapping(value = "auth/user", method = RequestMethod.GET)
    public ResultPojo getAuthenticatedUser(HttpServletRequest request)
    {
        ResultPojo result = new ResultPojo();

        String token = request.getHeader(tokenHeader);
        Map<String, Object> claims = jwtTokenUtil.getClaimsFromToken(token);
        // String username = jwtTokenUtil.getUsernameFromToken(token);
        // JwtUser user = (JwtUser)
        // userDetailsService.loadUserByUsername(username);

        UserUtils.getCurrentUser().toString();
        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(claims);
        return result;
    }

    @ApiOperation(value = "生成老系统的SSO密钥", httpMethod = "POST", response = String.class,
            notes = "返回临时的认证token，key为SSO_[token]，value为用户id，有效时间1分钟")
    @RequestMapping(value = "auth/sso", method = RequestMethod.POST)
    public ResultPojo genSsoToken(HttpServletRequest request)
    {
        ResultPojo result = new ResultPojo();

        // 生成临时token
        String token = IdGen.uuid();
        redisUtil.set("SSO_" + token, UserUtils.getCurrentUser().getId());

        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(token);
        return result;
    }

    @ApiOperation(value = "生成的SSO密钥，资源库使用", httpMethod = "POST", response = String.class,
            notes = "返回临时的认证token，key为SSO_[token]，value为用户名，有效时间1分钟")
    @RequestMapping(value = "auth/sso2", method = RequestMethod.POST)
    public ResultPojo genSsoToken2(HttpServletRequest request)
    {
        ResultPojo result = new ResultPojo();

        // 生成临时token
        String token = IdGen.uuid();
        redisUtil.set("SSO_" + token, UserUtils.getCurrentUser().getUsername());

        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(token);
        return result;
    }

    @ApiOperation(value = "生成BBS系统密钥", httpMethod = "POST", response = String.class,
            notes = "返回临时的认证token，key为BBS_[token]，value为用户，有效时间1分钟")
    @RequestMapping(value = "auth/bbs", method = RequestMethod.POST)
    public ResultPojo genBbsToken(HttpServletRequest request)
    {
        ResultPojo result = new ResultPojo();

        String token = request.getHeader(tokenHeader);

        JwtUser user = UserUtils.getCurrentUser();

        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
            String refreshedToken = jwtTokenUtil.refreshToken(token);

            result.setCode(ResultPojo.CODE_SUCCESS);
            result.setResult(refreshedToken);
        } else {
            result.setCode(ResultPojo.CODE_FAILURE);
        }
        return result;
    }
}